var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var session = require('express-session')
var bodyParser = require('body-parser');
var partials = require('express-partials');
var jsdom = require('jsdom');
var emojify = require('emojify.js');
var jwt = require('jsonwebtoken'); //used to create, sign, and verify tokens

var index = require('./routes/index');
var chat = require('./routes/chat');
var users = require('./routes/users');
var resource = require('./routes/resource');
var modules = require('./routes/module');
var visitors = require('./routes/visitors');
var authenticate = require('./routes/api/authenticate.js');
var login = require('./routes/login.js');
var logout= require('./routes/logout.js');

var user = require('./models/logDao.js');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
// app.locals._layoutFile = 'layout.html';
app.set('view engine', 'ejs');
app.set('superSecret', "nice day") // secret variable
app.use(partials());

/*
 *render html npm install consolidate mustache --save
 */
// var engine = require('consolidate'); app.engine('html', engine.mustache);
// app.set('view engine', 'html'); uncomment after placing your favicon in
// /public app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(cookieParser(app.get('superSecret')));
app.use(session({
    secret: app.get('superSecret'),
    resave: false, // don't save session if unmodified
    // saveUninitialized: true, // don't create session until something stored
    cookie: {maxAge: 60*1000} //单位毫秒
}));
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'views')));

app.use('/api/authenticate', authenticate);

//Token认证拦截器
app.use(function (req, res, next) {
    if (!req.session.user) {
    //如果请求的地址是登录则通过，进行下一个请求
        if(req.url.indexOf('/login') > -1 || req.originalUrl == 'logout'){
            next()
        }
        else{
            res.redirect('/login?redirect=' + req.originalUrl)
        }
    }else{
         next()
    }
})
app.use('/login', login);
app.use('/', index);
app.use('/visitors', visitors);
app.use('/users', users);
app.use('/chat', chat);
app.use('/resource', resource);
app.use('/module', modules);
app.use('/logout',logout);

// /* GET home page. */ app.use('/', function(req, res, next) {     //
// res.sendFile(__dirname + '/views/index/pages/index.html');
// res.render('index', {         title: '首页',         classes: ['active', '']
// }); }); catch 404 and forward to error handler
app.use(function (req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    // next(err);
    res.render('blank', {title: "404 Not Found"})
});

// error handlers development error handler will print stacktrace
if (app.get('env') === 'development') {
    app
        .use(function (err, req, res, next) {
            res.status(err.status || 500);
            res.render('error', {
                message: err.message,
                error: err
            });
        });
}

// production error handler no stacktraces leaked to user
app
    .use(function (err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: {}
        });
    });

module.exports = app;